package com.netty.server.handler;

import com.netty.entity.Message;
import com.netty.server.handler.MyHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xurongbei
 */
@ChannelHandler.Sharable
public class NettyServerHandler extends MyHandler<Message> {

    private List<ChannelHandlerContext> contextList = new ArrayList<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    }

    @Override
    public void channelRead(Channel channel, Message msg) {
        try {
           /* ByteBuf readBuffer = (ByteBuf) msg;
            byte[] tmpeDatas = new byte[readBuffer.readableBytes()];
            readBuffer.readBytes(tmpeDatas);
            String message = new String(tmpeDatas, "UTF-8");*/
            System.out.println("from client:" + msg.getContent());
            if ("exit".equals(msg.getTitle())) {
                channel.close();
                System.out.println("连接关闭");
                return;
            } else {
                System.out.println("to client");
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String line = br.readLine();
                channel.writeAndFlush(Unpooled.copiedBuffer(line.getBytes("UTF-8")));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("server excrptionCaughtvmethod run...");
        cause.printStackTrace();
        ctx.close();
    }
}
